/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.ActivityParticipation;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.IllegalOrphanException;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Involvement;
import pt.iasd.youthshelter.datamodel.service.InvolvementController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=InvolvementController.class)
public class InvolvementJpaController implements Serializable, InvolvementController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(Involvement involvement) {
        if (involvement.getActivityParticipationList() == null) {
            involvement.setActivityParticipationList(new ArrayList<ActivityParticipation>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            List<ActivityParticipation> attachedActivityParticipationList = new ArrayList<ActivityParticipation>();
            for (ActivityParticipation activityParticipationListActivityParticipationToAttach : involvement.getActivityParticipationList()) {
                activityParticipationListActivityParticipationToAttach = em.getReference(activityParticipationListActivityParticipationToAttach.getClass(), activityParticipationListActivityParticipationToAttach.getActivityParticipationPK());
                attachedActivityParticipationList.add(activityParticipationListActivityParticipationToAttach);
            }
            involvement.setActivityParticipationList(attachedActivityParticipationList);
            em.persist(involvement);
            for (ActivityParticipation activityParticipationListActivityParticipation : involvement.getActivityParticipationList()) {
                Involvement oldInvolvementIdOfActivityParticipationListActivityParticipation = activityParticipationListActivityParticipation.getInvolvementId();
                activityParticipationListActivityParticipation.setInvolvementId(involvement);
                activityParticipationListActivityParticipation = em.merge(activityParticipationListActivityParticipation);
                if (oldInvolvementIdOfActivityParticipationListActivityParticipation != null) {
                    oldInvolvementIdOfActivityParticipationListActivityParticipation.getActivityParticipationList().remove(activityParticipationListActivityParticipation);
                    em.merge(oldInvolvementIdOfActivityParticipationListActivityParticipation);
                }
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(Involvement involvement) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Involvement persistentInvolvement = em.find(Involvement.class, involvement.getId());
            List<ActivityParticipation> activityParticipationListOld = persistentInvolvement.getActivityParticipationList();
            List<ActivityParticipation> activityParticipationListNew = involvement.getActivityParticipationList();
            List<String> illegalOrphanMessages = null;
            for (ActivityParticipation activityParticipationListOldActivityParticipation : activityParticipationListOld) {
                if (!activityParticipationListNew.contains(activityParticipationListOldActivityParticipation)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ActivityParticipation " + activityParticipationListOldActivityParticipation + " since its involvementId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<ActivityParticipation> attachedActivityParticipationListNew = new ArrayList<ActivityParticipation>();
            for (ActivityParticipation activityParticipationListNewActivityParticipationToAttach : activityParticipationListNew) {
                activityParticipationListNewActivityParticipationToAttach = em.getReference(activityParticipationListNewActivityParticipationToAttach.getClass(), activityParticipationListNewActivityParticipationToAttach.getActivityParticipationPK());
                attachedActivityParticipationListNew.add(activityParticipationListNewActivityParticipationToAttach);
            }
            activityParticipationListNew = attachedActivityParticipationListNew;
            involvement.setActivityParticipationList(activityParticipationListNew);
            involvement = em.merge(involvement);
            for (ActivityParticipation activityParticipationListNewActivityParticipation : activityParticipationListNew) {
                if (!activityParticipationListOld.contains(activityParticipationListNewActivityParticipation)) {
                    Involvement oldInvolvementIdOfActivityParticipationListNewActivityParticipation = activityParticipationListNewActivityParticipation.getInvolvementId();
                    activityParticipationListNewActivityParticipation.setInvolvementId(involvement);
                    activityParticipationListNewActivityParticipation = em.merge(activityParticipationListNewActivityParticipation);
                    if (oldInvolvementIdOfActivityParticipationListNewActivityParticipation != null && !oldInvolvementIdOfActivityParticipationListNewActivityParticipation.equals(involvement)) {
                        oldInvolvementIdOfActivityParticipationListNewActivityParticipation.getActivityParticipationList().remove(activityParticipationListNewActivityParticipation);
                        em.merge(oldInvolvementIdOfActivityParticipationListNewActivityParticipation);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = involvement.getId();
                if (findInvolvement(id) == null) {
                    throw new NonexistentEntityException("The involvement with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Involvement involvement;
            try {
                involvement = em.getReference(Involvement.class, id);
                involvement.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The involvement with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<ActivityParticipation> activityParticipationListOrphanCheck = involvement.getActivityParticipationList();
            for (ActivityParticipation activityParticipationListOrphanCheckActivityParticipation : activityParticipationListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Involvement (" + involvement + ") cannot be destroyed since the ActivityParticipation " + activityParticipationListOrphanCheckActivityParticipation + " in its activityParticipationList field has a non-nullable involvementId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(involvement);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<Involvement> findInvolvementEntities() {
        return findInvolvementEntities(true, -1, -1);
    }

    @Override
    public List<Involvement> findInvolvementEntities(int maxResults, int firstResult) {
        return findInvolvementEntities(false, maxResults, firstResult);
    }

    private List<Involvement> findInvolvementEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Involvement.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public Involvement findInvolvement(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(Involvement.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getInvolvementCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Involvement> rt = cq.from(Involvement.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
